<?php

namespace app\home\controller\ump;

use app\home\controller\AuthController;
use services\FormBuilder as Form;
use app\home\model\ump\StoreCouponIssue as CouponIssueModel;
use app\home\model\ump\StoreCouponIssueUser;
use services\JsonService;
use think\facade\Route as Url;
use traits\CurdControllerTrait;
use services\UtilService as Util;

/**
 * 发布管理
 * Class StoreCouponIssue
 * @package app\home\controller\ump
 */
class StoreCouponIssue extends AuthController
{

    use CurdControllerTrait;

    protected $bindModel = CouponIssueModel::class;

    /**
     * 首页；所有的优惠券
     * @return string
     */
    public function index()
    {
        $where = Util::getMore([
            ['status', ''],
            ['coupon_title', '']
        ]);
        $this->assign(CouponIssueModel::stsypage($where));
        $this->assign('where', $where);
        return $this->fetch();
    }

    /**
     * 删除已经发布的优惠券
     * @param string $id
     * @return false|string
     */
    public function delete($id = '')
    {
        if (!$id) return JsonService::fail("参数错误");
        if (CouponIssueModel::edit(['is_del' => 1], $id, 'id'))
            return JsonService::successful('删除成功!');
        else
            return JsonService::fail('删除失败!');
    }

    /**
     * 编辑优惠券
     * @param string $id
     * @return false|string|void
     * @throws \FormBuilder\exception\FormBuilderException
     */
    public function edit($id = '')
    {
        if (!$id) return JsonService::fail('参数有误!');
        $issueInfo = CouponIssueModel::get($id);
        if (-1 == $issueInfo['status'] || 1 == $issueInfo['is_del']) return $this->failed('状态错误,无法修改');
        $f = [Form::radio('status', '是否开启', $issueInfo['status'])->options([['label' => '开启', 'value' => 1], ['label' => '关闭', 'value' => 0]])];
        $form = Form::make_post_form('状态修改', $f, Url::buildUrl('change_field', array('id' => $id, 'field' => 'status')));
        $this->assign(compact('form'));
        return $this->fetch('public/form-builder');
    }

    /**
     * 优惠券的领取记录
     * @param string $id
     * @return false|string
     */
    public function issue_log($id = '')
    {
        if (!$id) return JsonService::fail('参数有误!');
        $this->assign(StoreCouponIssueUser::systemCouponIssuePage($id));
        return $this->fetch();
    }
}